package com.linhui.rpc.proxy;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.linhui.common.model.User;
import com.linhui.common.service.UserService;
import com.linhui.rpc.model.RpcRequest;
import com.linhui.rpc.model.RpcResponse;
import com.linhui.rpc.serializer.Serializer;
import com.linhui.rpc.serializer.imp.JDKSerializer;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @author: 临晖
 * @since: 2024-05-11
 */
public class ServiceProxy implements InvocationHandler {

    private static final String REQUEST_ADDRESS = "http://localhost:8080";
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //指定序列化器
        //指定序列化器
        Serializer serializer = new JDKSerializer();
        //发请求 - 封装请求参数
        RpcRequest rpcRequest = new RpcRequest();
        rpcRequest.setArgs(args);
        rpcRequest.setParameterTypes(method.getParameterTypes());
        rpcRequest.setMethodName(method.getName());
        //通过方法获取类对象，然后获取全类名
        rpcRequest.setServiceName(method.getDeclaringClass().getName());
        try {
            byte[] bytes = serializer.serialize(rpcRequest);
            byte[] result;

            HttpResponse httpResponse = HttpRequest.post(REQUEST_ADDRESS).body(bytes).execute();

            result = httpResponse.bodyBytes();

            //反序列化
            RpcResponse rpcResponse = serializer.deserialize(result, RpcResponse.class);
            return rpcResponse.getData();

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
